// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// d [author] rhyme_lph
// D [email]  rhymelph@gmail.com
// g [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/account_entity.dart';
import 'package:finance_app/src/entities/payment_entity.dart';
import 'package:finance_app/src/provider/dashboard/bank/all_payment_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "allPaymentPage")
class AllPaymentPage extends StatefulWidget {
  final int accountId;
  final String accountName;

  const AllPaymentPage({Key key, this.accountId, this.accountName})
      : super(key: key);

  @override
  _AllPaymentPageState createState() => _AllPaymentPageState();
}

class _AllPaymentPageState extends State<AllPaymentPage>
    with PagePresenter<AllPaymentPage, AllPaymentProvider> {
  @override
  void initState() {
    provider.accountId = widget.accountId;
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: widget.accountName ?? S.current.all_transactions,
      );

  @override
  Widget get buildEmptyWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildTopWidget,
                Expanded(child: super.buildEmptyWidget),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Widget _buildBottomBar() => listBuilder<bool>(
        selector: (_, __) => __.buttonBarIsUp,
        builder: (BuildContext context, bool value, Widget child) =>
            AnimatedPositioned(
                duration: Duration(milliseconds: 300),
                left: 0.0,
                right: 0.0,
                bottom: value
                    ? MediaQuery.of(context).padding.bottom + getDp(40)
                    : -getDp(60),
                child: Center(
                  child: NormalFloatSvgButton(
                    onTap: provider.onNavAdd,
                    asset: A.assetsImagesDashboardAdd,
                  ),
                )),
      );

  Widget get buildTopWidget => Column(
        children: [
          AppSpaces.h20,
          SearchInputField(
            controller: provider.searchController,
            focusNode: provider.searchFocusNode,
          ),
          AppSpaces.h20,
          buildTimeSoreAndFilter(),
          AppSpaces.h20,
          _buildFilterList(),
        ],
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildTopWidget,
                Expanded(
                    child: listBuilder<
                        Tuple2<bool, Map<String, List<PaymentEntity>>>>(
                  selector: (_, __) => Tuple2(
                      __.hasUp, __.data == null ? null : Map.from(__.groupMap)),
                  builder: (BuildContext context,
                          Tuple2<bool, Map<String, List<PaymentEntity>>> value,
                          Widget child) =>
                      SmartRefresher(
                    controller: provider.refreshController,
                    onRefresh: provider.onRefresh,
                    onLoading: provider.onLoadMore,
                    enablePullUp: value.item1,
                    child: value.item2 == null
                        ? super.buildLoadingWidget
                        : value.item2.length == 0
                            ? super.buildEmptyWidget
                            : ListView(
                                controller: provider.controller,
                                children: _buildTransactionList(),
                              ),
                  ),
                )),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Row buildTimeSoreAndFilter() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildTimeSelect(),
        FilterButton(
          onPressed: provider.onShowFilter,
        ),
      ],
    );
  }

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int length, Widget child) => length == 0
            ? Container()
            : Container(
                height: getDp(32),
                margin: EdgeInsets.only(
                  bottom: getDp(5),
                  top: getDp(5),
                ),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) {
                    if (provider.rangeTime != null && length - 1 == index) {
                      return NormalChip(
                        title: provider.rangeTime,
                        onClose: provider.onClearRangeTime,
                      );
                    }
                    if (provider.currentSelectFilterAccount.length > 0 &&
                        provider.currentSelectFilterAccount.length - index >
                            0) {
                      return _buildAccountItem(context, index);
                    }
                    //最后的index
                    int _index =
                        index - provider.currentSelectFilterAccount.length;
                    return _buildFilterItem(context, _index);
                  },
                  itemCount: length,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(15),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.filterListLength);
  }

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  Widget _buildAccountItem(BuildContext context, int index) {
    return listBuilder<AccountEntity>(
        builder: (BuildContext context, AccountEntity value, Widget child) =>
            NormalChip(
              title: '${value.bankName} ${value.accountNumber ?? ''}',
              onClose: () => provider.onRemoveFilterBank(value),
            ),
        selector: (_, __) => __.currentSelectFilterAccount[index]);
  }

  List<Widget> _buildTransactionList() {
    List<Widget> child = [];
    for (final item in provider.groupMap.entries) {
      child.add(TransactionRecordTitleItem(
        title: item.key,
      ));
      child.addAll(List.generate(
          item.value.length,
          (index) => listBuilder<PaymentEntity>(
                selector: (_, __) => item.value[index],
                builder: (BuildContext context, PaymentEntity e, Widget child) {
                  return TransactionRecordItem(
                    onTap: () => provider.onNavPayment(e),
                    tag: TransactionTypeUtils.getTransactionType(
                        e.type == 'transfer'
                            ? '${e.type}_${e.flowType}'
                            : e.flowType),
                    name: e.name ?? '',
                    currencyCode: e.currencyCode,
                    time: S.current
                        .date_(DateTimeUtils.formatDateTimeString(e.issuedAt)),
                    amount: e.total?.toDouble(),
                  );
                },
              )));
    }
    return child;
  }
}
